<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="员工姓名" prop="userId" >
        <el-select v-model="form.userId" placeholder="请输入用户名" clearable filterable @keyup.native="queryUserByName" >
          <el-option v-for="item in userOptions" :key="item.id" :label="item.label" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="归属部门" prop="deptId">
        <treeselect v-model="queryParams.deptId" :options="deptOptions" :disable-branch-nodes="false" :show-count="true"
                    size="small" style="width: 200px" :default-expand-level="1"
                    placeholder="请选择归属部门"/>
      </el-form-item>
      <el-form-item label="日期" prop="date">

        <el-date-picker clearable size="small" style="width: 200px"
                        v-model="queryParams.date"
                        type="date"
                        format="yyyy-MM-dd"
                        value-format="yyyy-MM-dd"
                        placeholder="选择日期">
        </el-date-picker>

      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button icon="el-icon-refresh" @click="openDialog">智能排班</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:dailyschedule:export']"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table border v-loading="loading" :data="dailyscheduleList" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="员工" fixed="left"  show-tooltip-when-overflow  align="center" prop="nickName" />
      <el-table-column align="center" v-for="(item, index) in timecolumns" :render-header="renderheader" :label="item.lable" :prop="'scheime' + (index+1)" :column-key="'scheime'+(index+1)" :id="'cell_'+(index+1)" />

      <el-table-column label="操作" fixed="right" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:dailyschedule:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 智能排班创建需求 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="日期" prop="assignDate">
          <el-date-picker clearable size="small" style="width: 200px"
                          v-model="form.assignDate"
                          type="date"
                          format="yyyy-MM-dd"
                          value-format="yyyy-MM-dd"
                          placeholder="选择日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="岗位需求" prop="userId" v-for="(item, index) in form.requiredPosts">
          <span>
            <el-select v-model="item.postId" placeholder="岗位" >
              <el-option v-for="item in postOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </span>
          <span>
            <el-input v-model="item.requireNum" placeholder="需要人数" ></el-input>
          </span>
          <span>
            <el-time-select clearable size="small" v-model="item.assignTimeStart" :picker-options="{ start: '00:00', step: '00:30', end: '23:59' }"
                            type="time" format="HH:mm" value-format="HH:mm" placeholder="开始时间">
            </el-time-select>
          </span>
          <span>
            <el-time-select clearable size="small" v-model="item.assignTimeEnd" :picker-options="{ start: '00:00', step: '00:30', end: '23:59' }"
                            type="time" format="HH:mm" value-format="HH:mm" placeholder="结束时间">
            </el-time-select>
          </span>
          <span class="node-operation">
            <el-button class="el-icon-plus" @click="addRow">+</el-button>
            <el-button class="el-icon-delete" @click="removeRow(index)">-</el-button>
          </span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="clearPosts">清理方案缓存</el-button>
        <el-button type="primary" @click="aiScheduleAssign">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addDailyschedule,
  aiDailyschedule,
  delDailyschedule,
  exportDailyschedule,
  getDailyschedule,
  listDailyschedule,
  updateDailyschedule
} from "@/api/business/dailyschedule";

import {treeselect} from "@/api/selfcom/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {listUserLikeName} from "@/api/selfcom/user";
import {listTmppost} from "@/api/business/tmppost";

export default {
  name: "Dailyschedule",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 日排班表格数据
      dailyscheduleList: [],
      // 弹出层标题
      title: "",
      timecolumns: [],
      userOptions: [],
        // 部门树选项
      deptOptions: [],
      postOptions: [],
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {
        assignDate : undefined,
        requiredPosts: [{
          postId: undefined,
          requireNum: undefined,
          assignTimeStart: undefined,
          assignTimeEnd: undefined,
        }]
      },
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.inittimecolumns();
    this.getList();
    this.getTreeselect();
    this.queryPosts();
  },
  methods: {
    inittimecolumns() {
      for (let i = 1; i <= 72; i++) {
        let minutes = (i ) * 30;
        let hour = Math.floor(minutes / 60);
        let nextHour = hour;
        let start;
        let end;
        if((i % 2)  == 0) {
          start = "00";
          end = "30";
        } else {
          start = "30";
          end = "00";
          nextHour = nextHour + 1;
          if(nextHour == 24) {
            nextHour = "次日0";
          }
        }

        if(hour >= 24) {
          hour = "次日" + (hour - 24);
          nextHour = nextHour - 24;
        }

        let lable = hour + ":" + start + ",~," + nextHour + ":" + end;
        let col = {"lable": lable};
        this.timecolumns.push(col);
      }

    },

    renderheader(h, { column, $index }) {
      return h("div", {
        "style": {"line-height": "11px"}
      }, [
        h("div", {}, column.label.split(",")[0]),
        h("div", {}, column.label.split(",")[1]),
        h("div", {}, column.label.split(",")[2]),
      ]);
    },

    openDialog() {
      let cachedRequiredPosts = localStorage.getItem('requiredPosts');
      // console.log("read cache requiredPosts ", cachedRequiredPosts)
      if(!! cachedRequiredPosts) {
        this.form.requiredPosts = JSON.parse(cachedRequiredPosts);
      }
      this.form.assignDate = this.queryParams.date;
      this.open = true;
    },

    queryPosts() {
      listTmppost(this.queryParams).then(response => {
        this.postOptions = response.rows;
      });
    },

    clearPosts() {
      localStorage.removeItem('requiredPosts');
      this.form.requiredPosts = [];
      this.addRow();
    },

    aiScheduleAssign() {
      localStorage.setItem('requiredPosts', JSON.stringify(this.form.requiredPosts));
      aiDailyschedule(this.form).then(response => {
        if (response.code === 200) {
          this.msgSuccess("智能排班结束");
          this.open = false;
          this.getList();
        }
      });

    },
    addRow() {
      this.form.requiredPosts.push({
        postId: undefined,
        requireNum: undefined,
        assignTimeStart: undefined,
        assignTimeEnd: undefined,
      })
    },
    removeRow(index) {
      this.form.requiredPosts.splice(index, 1);
    },
    /** 查询日排班列表 */
    getList() {
      this.loading = true;
      listDailyschedule(this.queryParams).then(response => {
        this.dailyscheduleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加日排班";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDailyschedule(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改日排班";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateDailyschedule(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addDailyschedule(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除日排班编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delDailyschedule(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有日排班数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportDailyschedule(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    queryUserByName() {
      listUserLikeName(this.queryParams.userName).then(response => {
        this.userOptions = response.rows;
      });
    },

  }
};
</script>
<style>
.cell {
  line-height: 0px;
}
</style>
